<template>
  <div class="baseInfo">
    <div class="baseInfo-header" v-if="poStatus=='audited'">
      <el-button type="primary" size="small" @click="handleAdd">新增</el-button>
      <!-- <el-button type="danger" size="small" @click="handleDelete">删除</el-button> -->
    </div>
    <vxe-table
      border
      stripe
      ref="tableRef"
      size="small"
      :key="Date.now()"
      header-align="center"
      :row-config="rowConfig"
      :column-config="columnConfig"
      :data="tableDataList"
      @checkbox-change="checkboxChangeEvent"
      @checkbox-all="checkboxAll"
    >
      <!-- <vxe-column type="checkbox" width="40" fixed="left" v-if="poStatus=='audited'"></vxe-column> -->
      <vxe-column type="seq" width="70" align="center" fixed="left"></vxe-column>
      <vxe-column field="productName" width="200" show-overflow="title" align="center" title="产品名称"></vxe-column>
      <vxe-column field="productCode" width="200" show-overflow="title" align="center" title="产品代码"></vxe-column>
      <vxe-column field="productSpc" width="120" show-overflow="title" align="center" title="规格">
        <template #default="{ row }">
          <el-input :disabled="poStatus!=='audited'" v-model="row.productSpc" size="mini" placeholder="请输入规格"></el-input>
        </template>
      </vxe-column>
      <vxe-column field="batchCode" width="120" show-overflow="title" align="center" title="批次">
        <template #default="{ row }">
          <el-input :disabled="poStatus!=='audited'" v-model="row.batchCode" size="mini" placeholder="请输入批次"></el-input>
        </template>
      </vxe-column>
      <vxe-column field="unitOfMeasure" width="80" show-overflow="title" align="center" title="单位">
        <template #default="{ row }">
          <div style="width: 80px">
            {{ row.unitOfMeasure }}
          </div>
        </template>
      </vxe-column>
      <vxe-column field="quantity" width="150" show-overflow="title" align="center" title="订购数量">
        <template #default="{ row }">
          <el-input-number 
            size="mini"
            v-model="row.quantity" 
            :min="0"
            :disabled="poStatus!=='audited'"
            controls-position="right"  
          ></el-input-number>
        </template>
      </vxe-column>
      <vxe-column field="quantityCurr" width="150" show-overflow="title" align="center" title="可用库存数">
        <template #default="{ row }">
          <div style="width: 150px">
            {{ row.quantityCurr }}
          </div>
        </template>
      </vxe-column>
      <vxe-column field="discount" width="150" show-overflow="title" align="center" title="折扣(100%)">
        <template #default="{ row }">
          <el-input-number 
          size="mini"
          v-model="row.discount" 
          :min="0"
          :max="1"
          :disabled="poStatus!=='audited'"
          controls-position="right"
          ></el-input-number>
        </template>
      </vxe-column>
      <vxe-column field="taxRate" width="150" show-overflow="title" align="center" title="税率">
        <template #default="{ row }">
          <el-input-number 
          size="mini"
          v-model="taxRate" 
          :min="0"
          :max="1"
          disabled
          controls-position="right"
          ></el-input-number>
        </template>
      </vxe-column>
      <vxe-column field="price" width="150" show-overflow="title" align="center" title="单价(含税)">
        <template #default="{ row }">
          <!-- <el-input-number 
          size="mini"
          v-model="row.stdPrice" 
          :min="0"
          disabled
          controls-position="right"
          ></el-input-number> -->
          {{ row.stdPrice ? row.stdPrice.toFixed(2) : 0 }}
        </template>
      </vxe-column>
      <vxe-column field="totalPrice" width="150" show-overflow="title" align="center" title="总价(含税)">
        <template #default="{ row }">
          {{ Number((((row.stdPrice || 0) * (row.quantity || 0)) * (row.discount || 0)).toFixed(2)) }}
        </template>
      </vxe-column>
      <vxe-column field="priceExTax" width="150" show-overflow="title" align="center" title="单价(不含税)">
        <template #default="{ row }">
          <!-- <el-input-number 
          size="mini"
          v-model="row.priceExTax" 
          :min="0"
          :disabled="poStatus!=='audited'"
          controls-position="right"
          ></el-input-number> -->
          {{ taxRate ? (row.stdPrice / (1 + taxRate)).toFixed(2) : 0 }}
        </template>
      </vxe-column>
      <vxe-column field="totalPriceExTax" width="150" show-overflow="title" align="center" title="总价(不含税)">
        <template #default="{ row }">
          {{ taxRate > 0 ? Number(((((row.stdPrice / (1 + taxRate) || 0) * (row.quantity || 0)) * (row.discount || 0)) / taxRate).toFixed(2)) : 0 }}
        </template>
      </vxe-column>
      <vxe-column field="outPackageCount" width="150" show-overflow="title" align="center" title="外包装数量">
        <template #default="{ row }">
          <el-input-number 
          size="mini"
          v-model="row.outPackageCount" 
          :min="0"
          :disabled="poStatus!=='audited'"
          controls-position="right"
          ></el-input-number>
        </template>
      </vxe-column>
      <vxe-column field="remark" min-width="150" show-overflow="title" align="center" title="备注">
        <template #default="{ row }">
          <el-input :disabled="poStatus!=='audited'" v-model="row.remark" size="mini" placeholder="请输入备注"></el-input>
        </template>
      </vxe-column>
      <vxe-column width="200" align="center" title="操作" fixed="right" v-if="poStatus=='audited'">
        <template #default="{ row,index }">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(row)"
          >修改</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(row)"
          >删除</el-button>
        </template>
      </vxe-column>
    </vxe-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <ItemSelect 
      ref="itemSelect" 
      v-if="showItemSelect" 
      :selectIds="selectIds"
      @onSelected="onItemSelected" 
      @closeSelect="closeSelect"
    />
  </div>
</template>

<script>
import ItemSelect  from "@/components/itemSelect/multipleChoice.vue";
import { detailPurchaseOrder } from "@/api/mes/pro/purchaseOrder";
import { 
  addPurchaseOrderDetails,
  putPurchaseOrderDetails,
  delPurchaseOrderDetails,
} from "@/api/mes/purchase/purchaseOrderDetail";
export default {
  name: 'baseInfo',
  props: {
    cellId: undefined,
    poStatus: undefined,
    type: undefined,
    taxRate: undefined,
  },
  components: {
    ItemSelect,
  },
  data() {
    return {
      showItemSelect: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      form: {},
      tableData: [],
      columnConfig: {
        drag: true,
        resizable: true,
        storage: true,
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        align: 'center',
        headerAlign: 'center'
      },
      rowConfig: {
        drag: true,
        keyField: 'id',
        isHover: true,
      },
      total: 0,
      title: '',
      open: false,
      rules: {
        itemCode: [
          { required: false, message: '请输入物料编码', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '请输入产品(物料名称)', trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ],
      },
      ids: [],
      selectList: [], // 选中数据
      selectIds: [], // 选中数据的id
    }
  },
  created() {
    console.log('poStatus', this.poStatus);
    // this.getList();
  },
  computed: {
    tableDataList(){
      console.log('tableData', this.tableData, this.selectList);
      return [...this.tableData, ...this.selectList]
    }
  },
  watch: {
    cellId: {
      handler(val) {
        if(val&&this.type!=='新增'){
          this.getList();
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    /** 查询供应商退货行列表 */
    getList() {
      detailPurchaseOrder(this.cellId, this.queryParams).then(response => {
        this.tableData = response.rows?response.rows:[];
        this.total = response.total;
        this.selectIds = this.tableData.map(item => item.productId);
        console.log('response', response);
      });
      // this.$emit('getBaseInfoList', this.queryParams)
    },
    reset(){
      this.form = {
        id: undefined,
        poId: this.cellId,
        productName: undefined,
        batchCode: undefined,
        itemCode: undefined,
        unitOfMeasure: undefined,
        quantity: undefined,
        discount: undefined,
        price: undefined,
        totalPrice: undefined,
        priceExTax: undefined,
        totalPriceExTax: undefined,
        taxRate: undefined,
        outPackageCount: undefined,
      };
      this.resetForm('form');
    },
    handleAdd(){
      console.log('handleAdd',this.selectIds);
      this.handleSelectProduct();
    },
    handleEdit(row){
      this.title = '修改采购订单明细';
      this.open = true;
      this.form = {...row};
    },
    checkboxChangeEvent(checked){
      this.ids = checked.records.map(item => item.id)
      console.log(checked.records, this.ids);
    },
    checkboxAll(checked){
      this.ids = checked.records.map(item => item.id)
      console.log(checked.records, this.ids)
    },
    handleDelete(row){
      // console.log('handleDelete',row, this.tableData, this.selectList);
      // const ids = row.id || this.ids;
      this.$confirm('确定要删除该条数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = [...this.tableData];
        const data1 = [...this.selectList];
        this.tableData = data.filter(item => item.id !== row.id);
        this.selectList = data1.filter(item => item.id !== row.id);
        // delPurchaseOrderDetails(ids).then(response => {
          this.$message.success('删除成功')
      })
    },
    cancel(){
      this.open = false;
      this.reset();
      console.log('cancel');
    },
    submitForm(){
      const valid = this.tableDataList.every(item => {
        return item.productName && item.quantity>=0;
      })
      return valid;
    },
    //物料选择弹出框
    onItemSelected(obj){
      const that = this
      if(obj != undefined && obj != null){
        let ids = [];
        obj.forEach(item => ids.push(item.itemId));
        this.selectIds = [...new Set(ids)]
        const idss =that.tableData.map(i => i.productId)
        this.selectList = obj.map(item => {
          if(!idss.includes(item.itemId)){
            return {
              ...item,
              productId: item.itemId,
              productName: item.itemName,
              productCode: item.itemCode,
            }
          }
        }).filter(Boolean);
        console.log('obj', this.selectIds, obj);
      }
    },
    handleSelectProduct(){
      this.showItemSelect = true;
      this.$nextTick(()=>{
        this.$refs.itemSelect.showFlag = true;
      })
    },
    closeSelect(){
      this.showItemSelect = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.baseInfo{
  &-header{
    margin-bottom: 10px;
  }
}
</style>